package com.atguigu.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.seckill.config.MyRabbitMqConfig;
import com.atguigu.seckill.feign.CouponFeignService;
import com.atguigu.seckill.feign.ProductFeignService;
import com.atguigu.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.seckill.service.SeckillService;
import com.atguigu.seckill.to.SeckillSkuRedisTo;
import com.atguigu.seckill.vo.SeckillSessionWithSkus;
import com.atguigu.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author kabuda
 * @create 2023-01-11 20:07
 */
@Service
@Slf4j
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    //其实不需要static
    private final static String SESSION_CACHE_PREFIX = "seckill:sessions:";
    private final static String SECKILL_CACHE_PREFIX = "seckill:skus";
    private final static String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    @Override
    public void uploadSeckillSkuLatest3Days() {
        //1.扫描需要参加秒杀的活动
        R r = couponFeignService.getLatest3DaysSession();
        if (r.getCode() == 0) {
            List<SeckillSessionWithSkus> sessionData = r.getData(new TypeReference<List<SeckillSessionWithSkus>>() {
            });
            if(sessionData!=null){
                //上架商品（缓存到redis）
                //缓存活动信息
                saveSessionInfos(sessionData);
                //缓存活动关联信息
                saveSessionSkuInfos(sessionData);
            }

        }

    }


    @Override
    public List<SeckillSkuRedisTo> getCurrentSecKillSkus() {
        //1.获取当前时间的秒杀活动场次（规定一个时间段只有一个秒杀活动）
        //long time = new Date().getTime();
        LocalDateTime now = LocalDateTime.now();
        long time = now.toInstant(ZoneOffset.of("+8")).toEpochMilli();

        //seckill:sessions:1673594079000_1673594086000
        //seckill:sessions:1673594079001_1673594086001
        //.......
        Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
        for (String key : keys) {
            //将前缀替换成空串
            String replace = key.replace(SESSION_CACHE_PREFIX, "");
            //将1673594079000_1673594086000分割
            String[] s = replace.split("_");
            Long start = Long.parseLong(s[0]);
            Long end = Long.parseLong(s[1]);
            if (time >= start && time <= end) {
                //2.获取当前时间段秒杀的商品信息
                List<String> list = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_CACHE_PREFIX);
                //获取对应key的值集
                List<String> skus = hashOps.multiGet(list);
                if (skus != null && skus.size() > 0) {
                    //将json集合转化为对象
                    List<SeckillSkuRedisTo> collect = skus.stream().map(sku -> {
                        SeckillSkuRedisTo redisTo = JSON.parseObject((String) sku, SeckillSkuRedisTo.class);
                        //当前秒杀已经开始，需要返回随机码
                        //redisTo.setRandomCode(null);
                        return redisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }
            }
            //因为规定一个时间段只有一个秒杀活动，所以进来了直接break
            break;
        }

        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        String reg = "\\d_" + skuId;
        for (String key : keys) {
            if (Pattern.matches(reg, key)) {
                String sku = hashOps.get(key);
                SeckillSkuRedisTo redisTo = JSON.parseObject(sku, SeckillSkuRedisTo.class);
                //判断，如果不在秒杀活动时间内，不传递（暴漏）随机码，设置为空
                long now = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
                Long startTime = redisTo.getStartTime();
                Long endTime = redisTo.getEndTime();
                if (now < startTime || now > endTime) {
                    redisTo.setRandomCode(null);
                }
                return redisTo;
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        long s1 = System.currentTimeMillis();
        //获取当前用户的信息
        MemberRespVo user = LoginUserInterceptor.loginUser.get();

        //1、获取当前秒杀商品的详细信息从Redis中获取
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_CACHE_PREFIX);
        String skuInfoValue = hashOps.get(killId);
        if (StringUtils.isEmpty(skuInfoValue)) {
            return null;
        }
        //(合法性效验)
        SeckillSkuRedisTo redisTo = JSON.parseObject(skuInfoValue, SeckillSkuRedisTo.class);
        Long startTime = redisTo.getStartTime();
        Long endTime = redisTo.getEndTime();
        long currentTime = System.currentTimeMillis();
        //判断当前这个秒杀请求是否在活动时间区间内(效验时间的合法性)
        if (currentTime >= startTime && currentTime <= endTime) {

            //2、效验随机码和商品id
            String randomCode = redisTo.getRandomCode();
            String skuId = redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
            if (randomCode.equals(key) && killId.equals(skuId)) {
                //3、验证购物数量是否合理和库存量是否充足
                Integer seckillLimit = redisTo.getSeckillLimit();

                //获取信号量
                String seckillCount = redisTemplate.opsForValue().get(SKU_STOCK_SEMAPHORE + randomCode);
                Integer count = Integer.valueOf(seckillCount);
                //判断信号量是否大于0,并且买的数量不能超过库存
                if (count > 0 && num <= seckillLimit && count > num) {
                    //4、验证这个人是否已经买过了（幂等性处理）,如果秒杀成功，就去占位。userId-sessionId-skuId
                    //SETNX 原子性处理
                    String redisKey = user.getId() + "_" + skuId;
                    //设置自动过期(活动结束时间-当前时间)
                    Long ttl = endTime - currentTime;
                    Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                    if (aBoolean) {
                        //占位成功说明从来没有买过,分布式锁(获取信号量-1)
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                        //TODO 秒杀成功，快速下单
                        boolean semaphoreCount = false;
                        try {
                            semaphoreCount = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //保证Redis中还有商品库存
                        if (semaphoreCount) {
                            //创建订单号和订单信息发送给MQ
                            // 秒杀成功 快速下单 发送消息到 MQ 整个操作时间在 10ms 左右
                            String timeId = IdWorker.getTimeId();
                            SeckillOrderTo orderTo = new SeckillOrderTo();
                            orderTo.setOrderSn(timeId);
                            orderTo.setMemberId(user.getId());
                            orderTo.setNum(num);
                            orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                            orderTo.setSkuId(redisTo.getSkuId());
                            orderTo.setSeckillPrice(redisTo.getSeckillPrice());

                            rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",orderTo);
                            long s2 = System.currentTimeMillis();
                            log.info("耗时..." + (s2 - s1));
                            return timeId;
                        }
                    }
                }
            }
        }

        return null;
    }


    public void saveSessionInfos(List<SeckillSessionWithSkus> sessionData) {
        sessionData.stream().forEach(item -> {
            Long startTime = item.getStartTime().getTime();
            Long endTime = item.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;
            if (!redisTemplate.hasKey(key)) {
                List<String> collect = item.getRelationSkus().stream().map(i -> i.getPromotionSessionId().toString() + "_" + i.getSkuId().toString()).collect(Collectors.toList());
                //缓存活动信息
                redisTemplate.opsForList().leftPushAll(key, collect);
            }
        });
    }

    public void saveSessionSkuInfos(List<SeckillSessionWithSkus> sessionData) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(SECKILL_CACHE_PREFIX);
        sessionData.stream().forEach(item -> {
            item.getRelationSkus().stream().forEach(seckillVo -> {
                if (!hashOps.hasKey(seckillVo.getPromotionSessionId().toString() + "_" + seckillVo.getSkuId().toString())) {
                    SeckillSkuRedisTo seckillSkuRedisTo = new SeckillSkuRedisTo();
                    //1.保存sku基本信息
                    R r = productFeignService.getSkuinfo(seckillVo.getSkuId());
                    if (r.getCode() == 0) {
                        SkuInfoVo skuData = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        seckillSkuRedisTo.setSkuInfoVo(skuData);
                    }
                    //2.保存sku秒杀信息
                    BeanUtils.copyProperties(seckillVo, seckillSkuRedisTo);

                    //3.保存开启结束时间
                    seckillSkuRedisTo.setStartTime(item.getStartTime().getTime());
                    seckillSkuRedisTo.setEndTime(item.getEndTime().getTime());
                    //4.保存随机码 seckill?skuId=1&randomCode=fdfdfd; 确保公平
                    String randomCode = UUID.randomUUID().toString().replace("_", "");
                    seckillSkuRedisTo.setRandomCode(randomCode);

                    //5.使用库存作为分布式的信号量，限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                    //使用当前商品秒杀数量作为信号量
                    semaphore.trySetPermits(seckillVo.getSeckillCount().intValue());

                    String jsonString = JSON.toJSONString(seckillSkuRedisTo);

                    hashOps.put(seckillVo.getPromotionSessionId().toString() + "_" + seckillVo.getSkuId().toString(), jsonString);
                }
            });
        });
    }
}
